import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { PrismaService } from 'prisma.service';
import { isEmail } from 'class-validator';
import { Request } from 'express';
import { JwtSign } from 'src/auth/jwt.sign';
import { User } from './entities/user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto'
import { decrypt as rsaDecrypt } from '../common/utils/rsa';
import { encrypt } from '../common/utils/crypt';

const select = {
  id: true,
  name: true,
  phone: true,
  email: true,
  avatar: true,
  desc: true,
  lastLoginTime: true,
  createdTime: true,
  updateTime: true
}

@Injectable()
export class UserService {
  constructor(private prisma: PrismaService) {}

  async create(createUserDto: CreateUserDto): Promise<User | null> {
    const { phone, password, email } = createUserDto
    if (email && !isEmail(email)) {
      throw new HttpException("邮箱格式错误", HttpStatus.BAD_REQUEST)
    }
    const existUser = await this.prisma.user.findFirst({
      where: {
        phone
      }
    })
    if(existUser){
      throw new HttpException("手机号码已存在", HttpStatus.BAD_REQUEST)
    }
    const hashPassword = rsaDecrypt(password)
    return await this.prisma.user.create({
      data: {
        ...createUserDto,
        password: encrypt(hashPassword)
      },
      select
    })
  }

  findPage(condition: User) {
    return this.prisma.user.findMany({
      where: condition,
      select
    });
  }

  findAll(condition: User) {
    return this.prisma.user.findMany({
      where: condition,
      select
    });
  }

  findOne(id: string) {
    return this.prisma.user.findFirst({
      where: {
        id
      },
      select
    });
  }

  findCur(request: Request) {
    const { userId } = request.user as JwtSign
    if (!userId){
      throw new HttpException('用户不存在', HttpStatus.OK)
    }
    return this.findOne(userId)
  }

  update(updateUserDto: UpdateUserDto, request: Request) {
    let { id } = updateUserDto
    if (!id) {
      const { userId } = request.user as JwtSign
      id = userId
    }
    if (!id){
      throw new HttpException('用户不存在', HttpStatus.OK)
    }
    return this.prisma.user.update({
      where: {id},
      data: updateUserDto
    })
  }

  remove(id: string) {
    return `This action removes a #${id} user`;
  }
}
